#include "netclient.h"

NetClient::NetClient(QString ip, int pot, QObject *parent) : QObject(parent)
{
    cli=nullptr;
    ipaddr=ip;
    port=pot;
    RECONNECTTIMES=5000;
    isreconnect=true;
}
void NetClient::starting()
{
    isreconnect=true;
    newconnect();
}
void NetClient::close()
{
    this->isreconnect=false;
    this->cli->close();
}
void NetClient::setreconnecttime(int timespan)
{
    this->RECONNECTTIMES=timespan;
}

void NetClient::setipport(QString ip, int portnum)
{
    this->ipaddr=ip;
    this->port=portnum;
    QTimer::singleShot(RECONNECTTIMES,this,SLOT(newconnect()));
}

void NetClient::newconnect()
{
    if(cli!=nullptr)
    {
        cli->close();
        delete cli;
        cli=nullptr;
    }
    cli=new QTcpSocket;
    connect(cli,SIGNAL(connected()),this,SLOT(isconneced()));
    connect(cli,SIGNAL(readyRead()),this,SLOT(readEvent()));
    connect(cli,SIGNAL(disconnected()),this,SLOT(dropped()));
    connect(cli,SIGNAL(error(QAbstractSocket::SocketError)),this,SLOT(error(QAbstractSocket::SocketError)));
    cli->connectToHost(ipaddr,port);

}
void NetClient::isconneced()
{
    if(cli->open(QIODevice::ReadWrite))
    {
        qDebug()<<"connect success,and is opened !";
    }
    else
    {
        qDebug()<<"connect faild !";
        QTimer::singleShot(RECONNECTTIMES,this,SLOT(newconnect()));
    }
}

void NetClient::dropped()
{
    qDebug()<<"network dropped!! ";
}
void NetClient::error(QAbstractSocket::SocketError)
{
    qDebug()<<"network dropped , 5 seconds after the reconnection !! ";
    qDebug() << cli->errorString();
    if(!isreconnect)
    {
        return;
    }
    QTimer::singleShot(RECONNECTTIMES,this,SLOT(newconnect()));
}
void NetClient::readevent()
{

    QByteArray arr=cli->readAll();
    QString str;
    for(int i=0;i<arr.length();i++)
    {
        str+=QString::number((uchar)arr.at(i),16)+" ";
    }
    qDebug()<<"cloud read:"+str;;
    emit senddata(arr);

}
void NetClient::writevent(const QByteArray dataarr)
{
    //qDebug(dataarr);
    if(!cli->isOpen()||!cli->isWritable())
    {
        qDebug()<<"net work can not enable !";
        return;
    }
    int len= cli->write(dataarr);
    qDebug()<<"send lenght: "+QString::number(len);
}
